package com.guli.cart.controller;
/*
 * @Author 罗俊
 * @date 2020/11/8 - 9:47 上午
 *
 */

import com.guli.cart.service.CartService;
import com.guli.common.pojo.vo.CartVo;
import com.guli.common.pojo.vo.SkuItemVo;
import com.guli.common.utils.R;
import com.guli.common.valid.UpdateGroup;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

/**
 * 购物车 controoler ，包含 离线购物车 与 在线购物车
 * */
@RestController
@RequestMapping("/cart")
@Slf4j
public class CartController {

    @Resource
    CartService cartService;

    @GetMapping("/getCartList")
    @ApiOperation("获取用户购物车")
    public R getCartList(){

        CartVo cartVo = cartService.getCartList();
//        log.info("获取用户购物车【{}】",cartVo.getItems());

        return R.ok().put("cart",cartVo);
    }

    @Deprecated // 投机的办法，绕过了 cookie，不安全
    @GetMapping("/getSelectedItemForPayment/{memberId}")
    @ApiOperation("获取选中的商品，用于下订单")
    public CartVo getSelectedItemForPayment(@PathVariable("memberId")Long memberId){
        return cartService.getSelectedItemForPayment(memberId);
    }

    @GetMapping("/getSkuOfCartBySkuId/{skuId}")
    @ApiOperation("根据skuId来获取用户的购物车信息")
    public R getSkuOfCartBySkuId(@PathVariable("skuId")Long skuId){

        SkuItemVo skuItemVo = cartService.getSkuOfCartBySkuId(skuId);

        return R.ok().put("data",skuItemVo);
    }


    @GetMapping("/addToCart/{skuId}/{number}")
    @ApiOperation("添加到购物车")
    public R addToCart(@PathVariable("skuId")Long skuId,@PathVariable("number") Integer number) throws ExecutionException, InterruptedException {

        SkuItemVo skuItemVo = cartService.addToCart(skuId, number);

        return R.ok().put("data",skuItemVo);
    }

    @PostMapping("/updateCartByUserKey")
    @ApiOperation("更新用户的购物车")
    public R updateCartByUserKey(@RequestBody @Validated(UpdateGroup.class) SkuItemVo skuItemVo){

        SkuItemVo skuItemVo1 = cartService.updateCartByUserKey(skuItemVo);

        return R.ok().put("data",skuItemVo1);
    }

    @DeleteMapping("/deleteItemByUserKey")
    @ApiOperation("根据userKey删除购物车中的商品")
    public R deleteItemByUserKey(@RequestParam Long skuId){
        cartService.deleteItemByUserKey(skuId);

        return R.ok();
    }
}
